/* 
 *   Date       Developer   Description
 *   
 *
 *   Classname:  zzz.test.component.mock.Test01
 * 
 *   Date:   2014-3-7
 * 
 *   The source code contained in this listing is proprietary to
 *   HLJ POST YITONG INFO-NET CO.,LTD.
 * 
 *   Unauthorized copying, adaptation, distribution, use, or display
 *   is strictly prohibited.
 *   This software is Copyright 2014 HLJ POST YITONG INFO-NET CO.,LTD.
 */
package com.titan.demo.camel.sample.component.mock;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.Builder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;

import com.titan.demo.camel.utils.RunCamel;


/**
 * mock的基本用法
 *
 */
public class Test01 {

    public static void main(String[] args) {
    	new RunCamel() {
			protected void execute(CamelContext context, ProducerTemplate producer, ConsumerTemplate consumer) throws Exception {
	            MockEndpoint endpoint = context.getEndpoint("mock:result", MockEndpoint.class);

	            // 设置验证信息
	            endpoint.expectedMessageCount(4);  // 期望发送了4条信息
	            endpoint.expectsAscending(Builder.header("counter").convertTo(Number.class));  // 测试信息头内容是升序的
	            endpoint.expectedBodiesReceived("b11", "b12", "b13", "b14");
	            endpoint.expectedBodiesReceived(listOfMessages(11, 12, 13, 14));
	            endpoint.expectedHeaderValuesReceivedInAnyOrder("counter", 11, 12, 13, 14);
	            endpoint.expectsNoDuplicates(Builder.header("counter"));
	            
	            // 发送消息
	            for (int i = 11; i < 15; i++) {
	                String body = createTestMessage(i);
	                producer.sendBodyAndHeader("direct:a", body, "counter", i);
	            }
	            
	            // 设置验证都能满足
	            endpoint.setResultWaitTime(2000);
	            endpoint.assertIsSatisfied();
			}
    	}.run(new RouteBuilder() {
            public void configure() {
                from("direct:a").to("mock:result");
            }
        });
    }

    private static String createTestMessage(int counter) {
        return "b" + counter;
    }
    private static Object[] listOfMessages(int... counters) {
        List<String> list = new ArrayList<String>(counters.length);
        for (int counter : counters) {
            list.add(createTestMessage(counter));
        }
        return list.toArray();
    }

}

